package icu.cqcai.xinsi.mapper;

import icu.cqcai.xinsi.domain.ChatMessage;
import org.apache.ibatis.annotations.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 聊天消息Mapper接口
 */
@Mapper
public interface ChatMessageMapper {

    /**
     * 插入聊天消息
     */
    @Insert("INSERT INTO chat_messages (session_id, user_id, message_type, content, status, create_time, response_time, coze_user_id) " +
            "VALUES (#{sessionId}, #{userId}, #{messageType}, #{content}, #{status}, #{createTime}, #{responseTime}, #{cozeUserId})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertChatMessage(ChatMessage chatMessage);

    /**
     * 根据会话ID获取消息列表
     */
    @Select("SELECT * FROM chat_messages WHERE session_id = #{sessionId} AND status = 1 ORDER BY create_time ASC")
    List<ChatMessage> selectMessagesBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 根据会话ID获取消息列表（分页）
     */
    @Select("SELECT * FROM chat_messages WHERE session_id = #{sessionId} AND status = 1 " +
            "ORDER BY create_time ASC LIMIT #{offset}, #{limit}")
    List<ChatMessage> selectMessagesBySessionIdWithPage(@Param("sessionId") Long sessionId, 
                                                       @Param("offset") int offset, 
                                                       @Param("limit") int limit);

    /**
     * 根据用户ID获取最近的消息
     */
    @Select("SELECT * FROM chat_messages WHERE user_id = #{userId} AND status = 1 " +
            "ORDER BY create_time DESC LIMIT #{limit}")
    List<ChatMessage> selectRecentMessagesByUserId(@Param("userId") Long userId, @Param("limit") int limit);

    /**
     * 根据会话ID获取最近的消息（用于上下文）
     */
    @Select("SELECT * FROM chat_messages WHERE session_id = #{sessionId} AND status = 1 " +
            "ORDER BY create_time DESC LIMIT #{limit}")
    List<ChatMessage> selectRecentMessagesBySessionId(@Param("sessionId") Long sessionId, @Param("limit") int limit);

    /**
     * 根据消息ID获取消息
     */
    @Select("SELECT * FROM chat_messages WHERE id = #{messageId} AND status = 1")
    ChatMessage selectMessageById(@Param("messageId") Long messageId);

    /**
     * 删除消息（软删除）
     */
    @Update("UPDATE chat_messages SET status = 0 WHERE id = #{messageId}")
    int deleteMessage(@Param("messageId") Long messageId);

    /**
     * 删除会话的所有消息（软删除）
     */
    @Update("UPDATE chat_messages SET status = 0 WHERE session_id = #{sessionId}")
    int deleteMessagesBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 获取会话的消息数量
     */
    @Select("SELECT COUNT(*) FROM chat_messages WHERE session_id = #{sessionId} AND status = 1")
    int countMessagesBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 获取用户的消息总数
     */
    @Select("SELECT COUNT(*) FROM chat_messages WHERE user_id = #{userId} AND status = 1")
    int countMessagesByUserId(@Param("userId") Long userId);

    /**
     * 获取会话的第一条用户消息（用于生成会话标题）
     */
    @Select("SELECT * FROM chat_messages WHERE session_id = #{sessionId} AND message_type = 'user' AND status = 1 " +
            "ORDER BY create_time ASC LIMIT 1")
    ChatMessage selectFirstUserMessageBySessionId(@Param("sessionId") Long sessionId);

    /**
     * 根据时间范围查询消息
     */
    @Select("SELECT * FROM chat_messages WHERE user_id = #{userId} AND status = 1 " +
            "AND create_time BETWEEN #{startTime} AND #{endTime} ORDER BY create_time DESC")
    List<ChatMessage> selectMessagesByTimeRange(@Param("userId") Long userId,
                                               @Param("startTime") LocalDateTime startTime,
                                               @Param("endTime") LocalDateTime endTime);

    /**
     * 根据用户ID获取最近几小时内的消息（用于上下文）
     */
    @Select("SELECT * FROM chat_messages WHERE user_id = #{userId} AND status = 1 " +
            "AND create_time >= DATE_SUB(NOW(), INTERVAL #{hours} HOUR) " +
            "ORDER BY create_time ASC LIMIT #{limit}")
    List<ChatMessage> selectRecentMessagesByUserIdAndHours(@Param("userId") Long userId, 
                                                          @Param("hours") int hours, 
                                                          @Param("limit") int limit);

    /**
     * 搜索消息内容
     */
    @Select("SELECT * FROM chat_messages WHERE user_id = #{userId} AND status = 1 " +
            "AND content LIKE CONCAT('%', #{keyword}, '%') ORDER BY create_time DESC LIMIT #{limit}")
    List<ChatMessage> searchMessagesByContent(@Param("userId") Long userId, 
                                             @Param("keyword") String keyword, 
                                             @Param("limit") int limit);
} 